package cn.edu.ecut.se2024.controller;

import cn.edu.ecut.se2024.model.contracts_management.Contract;
import cn.edu.ecut.se2024.service.ContractsManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class ContractsManagementController {

    private final ContractsManagementService contractsManagementService;

    @Autowired
    public ContractsManagementController(ContractsManagementService contractsManagementService) {
        this.contractsManagementService = contractsManagementService;
    }

    @GetMapping("/")
    public String showContractList(Model model) {
        List<Contract> contracts = contractsManagementService.getAllContracts();
        model.addAttribute("contracts", contracts);
        return "contractList";
    }

    @PostMapping("/createContract")
    public String createContract(@ModelAttribute Contract contract) {
        contractsManagementService.insertContract(contract);
        return "redirect:/";
    }

    @GetMapping("/updateContract")
    public String showUpdateContractForm(@RequestParam("contractId") int contractId, Model model) {
        Contract contract = contractsManagementService.findContractById(contractId);
        model.addAttribute("contract", contract);
        return "updateContractForm";
    }

    @PostMapping("/updateContract")
    public String updateContract(@ModelAttribute Contract contract) {
        contractsManagementService.updateContract(contract);
        return "redirect:/";
    }

    @GetMapping("/deleteContract")
    public String deleteContract(@RequestParam("contractId") int contractId) {
        contractsManagementService.deleteContract(contractId);
        return "redirect:/";
    }
}